﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using System.Data;

namespace CheckingServiceDongBo
{
    public class Store
    {
        private static string _ConnectString = "";
        public Store(string connectString)
        {
            _ConnectString = connectString;
            LoadFromDB();
            if (DataTable != null) _DataRow = DataTable.NewRow();
        }

        #region DataTable property
        private DataTable _DataTable;
        public DataTable DataTable
        {
            get
            {
                return _DataTable;
            }
        }
        #endregion

        #region DataRow property
        protected DataRow _DataRow = null;
        public DataRow DataRow
        {
            get
            {
                return _DataRow;
            }
            set
            {
                _DataRow = value;
            }
        }
        #endregion

        #region ID property
        public Guid ID
        {
            get
            {
                if (_DataRow["ID"] is Guid)
                    return (Guid)_DataRow["ID"];
                else
                    return Guid.Empty;
            }
            set
            {
                _DataRow["ID"] = value;
            }
        }
        #endregion

        #region StoreID property
        public int StoreID
        {
            get
            {
                return (int)_DataRow["StoreID"];
            }
            set
            {
                _DataRow["StoreID"] = value;
            }
        }
        #endregion

        #region Name property
        public string Name
        {
            get
            {
                return (string)_DataRow["Name"];
            }
            set
            {
                if (_DataRow != null) _DataRow["Name"] = value;
            }
        }
        #endregion

        #region Owner property
        public bool Owner
        {
            get
            {
                return (bool)_DataRow["Owner"];
            }
            set
            {
                _DataRow["Owner"] = value;
            }
        }
        #endregion

        public virtual void InsertToDB()
        {
            SqlConnection con = new SqlConnection(_ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                string values = ""; string listOfColumns = "";
                foreach (DataColumn column in this.DataRow.Table.Columns)
                {
                    values = values + "@" + column.ColumnName + ", ";
                    listOfColumns = listOfColumns + column.ColumnName + ", ";
                    cmd.Parameters.AddWithValue(column.ColumnName, DataRow[column.ColumnName]);
                }

                if (values.EndsWith(", ")) values = values.Substring(0, values.Length - 2);
                if (listOfColumns.EndsWith(", ")) listOfColumns = listOfColumns.Substring(0, listOfColumns.Length - 2);

                cmd.CommandText = string.Format("INSERT INTO [{0}]({1}) VALUES({2})",
                                                    this.DataRow.Table.TableName, listOfColumns, values);
                cmd.ExecuteNonQuery();
                if (this.DataRow.Table.Rows.IndexOf(this.DataRow) < 0) this.DataRow.Table.Rows.Add(this.DataRow);
            }
            catch (SqlException sqlEx)
            {
                throw new Exception(CommonLib.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
            }
            finally
            {
                con.Close();
            }
        }
        public virtual void UpdateToDB()
        {
            SqlConnection con = new SqlConnection(_ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();

                string values = "";
                foreach (DataColumn column in this.DataRow.Table.Columns)
                {
                    if (column.ColumnName != "ID")
                    {
                        values += string.Format("{0} = @{0}, ", column.ColumnName);
                        cmd.Parameters.AddWithValue(column.ColumnName, DataRow[column.ColumnName]);
                    }
                }

                if (values.EndsWith(", ")) values = values.Substring(0, values.Length - 2);

                cmd.CommandText = string.Format("UPDATE [{0}] SET {1} WHERE StoreID= '{2}'",
                                                    this.DataRow.Table.TableName,
                                                    values,
                                                    this.DataRow["StoreID"]);
                cmd.ExecuteNonQuery();
            }
            catch (SqlException sqlEx)
            {
                throw new Exception(CommonLib.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                //Usual Code
            }
            finally
            {
                con.Close();
            }
        }
        public virtual void DeleteFromDB()
        {
            SqlConnection con = new SqlConnection(_ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("DELETE FROM [{0}] WHERE StoreID = '{1}'",
                                                    this.DataRow.Table.TableName,
                                                    this.DataRow["StoreID"]);
                cmd.ExecuteNonQuery();
                _DataRow.Delete();
            }
            catch (SqlException sqlEx)
            {
                throw new Exception(CommonLib.GetSqlExceptionMessage(sqlEx));
            }
            catch (Exception ex)
            {
                //Usual Code
            }
            finally
            {
                con.Close();
            }
        }

        public void LoadFromDB()
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = _ConnectString;
                DataTable listStoreName = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = "SELECT * FROM Store";
                    da.SelectCommand = cmd;
                    da.Fill(listStoreName);
                    _DataTable = listStoreName;
                    _DataTable.TableName = "Store";
                }
                catch (Exception ex)
                {
                    _DataTable = null;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }

        public bool CheckByStoreID(int storeID)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = _ConnectString;
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT * FROM Store WHERE StoreID = {0}", storeID);
                    da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    if (dt.Rows.Count > 0) return true;
                    else return false;
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }
        public bool CheckByName(string name)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = _ConnectString;
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT * FROM Store WHERE Name = '{0}'", name);
                    da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    if (dt.Rows.Count > 0) return true;
                    else return false;
                }
                catch (Exception ex)
                {
                    return false;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }

        public static Store GetByStoreID(string connectionString, int storeID)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = connectionString;
                _ConnectString = connectionString;
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT * FROM Store WHERE StoreID = {0}", storeID);
                    da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);

                    Store store = new Store(_ConnectString);
                    store.StoreID = (int)dt.Rows[0]["StoreID"];
                    store.Name = dt.Rows[0]["Name"].ToString();
                    if (dt.Rows[0]["Owner"] is bool) store.Owner = (bool)dt.Rows[0]["Owner"];
                    else store.Owner = false;

                    return store;
                }
                catch (Exception ex)
                {
                    return null;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }
        public static Store GetByID(string connectionString, Guid ID)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = connectionString;
                _ConnectString = connectionString;
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT * FROM Store WHERE ID = '{0}'", ID);
                    da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);

                    Store store = new Store(_ConnectString);
                    store.ID = (Guid)dt.Rows[0]["ID"];
                    store.StoreID = (int)dt.Rows[0]["StoreID"];
                    store.Name = dt.Rows[0]["Name"].ToString();
                    if (dt.Rows[0]["Owner"] is bool) store.Owner = (bool)dt.Rows[0]["Owner"];
                    else store.Owner = false;

                    return store;
                }
                catch (Exception ex)
                {
                    return null;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }
        public static Store GetByName(string connectionString, string name)
        {
            using (SqlConnection con = new SqlConnection())
            {
                con.ConnectionString = connectionString;
                _ConnectString = connectionString;
                SqlDataAdapter da = new SqlDataAdapter();
                try
                {
                    con.Open();
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandText = string.Format("SELECT * FROM Store WHERE Name = '{0}'", name);
                    da.SelectCommand = cmd;
                    DataTable dt = new DataTable();
                    da.Fill(dt);

                    Store store = new Store(_ConnectString);
                    store.StoreID = (int)dt.Rows[0]["StoreID"];
                    store.Name = dt.Rows[0]["Name"].ToString();
                    store.Owner = (bool)dt.Rows[0]["Owner"];

                    return store;
                }
                catch (Exception ex)
                {
                    return null;
                }
                finally
                {
                    if (con.State == ConnectionState.Open) con.Close();
                }
            }
        }
    }
}
